declare const ue: any;
declare const ue5: any;

export interface UeResult {
  code: string;
  status: number;
  msg: string;
  data: any;
}

function uuidv4() {
  var d = new Date().getTime();
  var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
  });
  return uuid;
}

export function send(code: String, data: String = "", time = 1) {
  if (!isClientApp()) {
    console.error("请在客户端运行");
    return Promise.reject('请在客户端运行')
  }
  return new Promise<UeResult>((resolve) => {
    const uuid = uuidv4();
    ue.interface[uuid] = (res) => {
      // console.log('回调',res)
      resolve(res);
    };
    // console.log( data);
    ue.interface.broadcast(code, JSON.stringify(data), uuid); //这行代码好像有点问题啊
    setTimeout(() => {
      delete ue.interface[uuid];
    }, 1e3 * Math.max(1, time || 0));
  });
}

export function isClientApp() {
  return "object" == typeof ue && "object" == typeof ue.interface && "function" == typeof ue.interface.broadcast;
}

export function registerMessageHandle(callback) {
  ue.interface.ueToWeb = callback;
}

export function post(code, data: Object = {}) {
  //这里转了字符串
  return send(
    "webToUe",
    JSON.stringify({
      code: code,
      msg: "",
      data,
    })
  ).then((res: any) => {
    let result = res;
    if (typeof result == "string") {
      result = JSON.parse(result);
    }
    // 全局回调处理
    if (result.status != 200) {
      handleUeMsgError(result);
    }
    return result.data;
  });
}

/**客户端失败消息处理 */
export function handleUeMsgError(res) {
  console.error(res);
}

export function registerReady(callback) {
  ue.interface.webReady = callback;
}


export function registerMttq(callback) {
  ue.interface.mttq = callback;
}


